package edu.zut.controller;

import edu.zut.pojo.UserInfo;
import edu.zut.service.UserService;
import edu.zut.util.MailSendUtil;
import edu.zut.util.ZYMUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    //自动注入
    @Autowired
    private UserService userService;

    @GetMapping("/toReg")
    public String toReg(){
        return "registration";
    }

    /**
     * @ResponseBody ：定义在方法上，表示当前请求返回的数据是通过响应体返回，
     *      不会触发页面刷新
     *      异步交互中，返回map后自动转成json对象
     *      返回list集合会自动转成json数组
     */
    @GetMapping("/validateEmail")
    @ResponseBody
    public Map validateEmail(String email){
        Map<String,Object> map = new HashMap<>();
        System.out.println("email = " + email);
        boolean flag = userService.getInfoByEmail(email);
        if (flag){
            map.put("msg","fail");
            return map;
        }
        map.put("msg","success");

        return map;
    }

    //@RequestBody :post异步中，请求参数是在请求体中
    @PostMapping("/validateEmail")
    @ResponseBody
    public Map validateEmail2(@RequestBody UserInfo userInfo){
        Map<String,Object> map = new HashMap<>();
        System.out.println("email = " + userInfo.getEmail());
        boolean flag = userService.getInfoByEmail(userInfo.getEmail());
        if (flag){
            map.put("msg","fail");
            return map;
        }
        map.put("msg","success");
        return map;
    }

    @Resource
    private MailSendUtil mailSendUtil;
    /**
     * 忘记密码发送邮件
     */
    @PostMapping("/sendEmail")
    @ResponseBody
    public Map sendMail(@RequestBody String email){
        Map<String,Object> map = new HashMap<>();
        String zym = ZYMUtil.createZYM();
        mailSendUtil.send(email,zym);
        boolean flag = userService.updateYZM(email,zym);
        if (flag)
            map.put("msg","success");
        else
            map.put("msg","fail");
        return map;
    }


    @GetMapping("/query")
    @ResponseBody
    public List<UserInfo> query(){
        List<UserInfo> infos = userService.queryList();
        return infos;
    }
}
